package com.qqbot.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.StringTokenizer;

/**
 * 工具类
 *
 * @author 付亚全
 */
public class CommonUtil {

    /**
     * 文字转图片
     *
     * @param text
     * @return
     * @throws IOException
     */
    public static InputStream textToPicture(String text) throws IOException {
        int width = 400;
        int height = 110;
        int x = 10;
        int y = 30;
        int fontSize = 20;
        String fontName = "微软雅黑";
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = image.createGraphics();
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, width, height);
        g2d.setColor(Color.BLACK);
        g2d.setFont(new Font(fontName, Font.PLAIN, fontSize));
        FontMetrics fm = g2d.getFontMetrics();
        int lineHeight = fm.getHeight();
        StringTokenizer tokenizer = new StringTokenizer(text, "\n");
        while (tokenizer.hasMoreTokens()) {
            String line = tokenizer.nextToken();
            int lineWidth = fm.stringWidth(line);
            if (lineWidth > width - x * 2) {
                int start = 0;
                int end = line.length();
                while (start < end) {
                    int len = end - start;
                    while (fm.stringWidth(line.substring(start, start + len)) > width - x * 2) {
                        len--;
                    }
                    String subLine = line.substring(start, start + len);
                    g2d.drawString(subLine, x, y);
                    y += lineHeight;
                    start += len;
                }
            } else {
                g2d.drawString(line, x, y);
                y += lineHeight;
            }
        }
        g2d.dispose();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", bos);
        InputStream is = new ByteArrayInputStream(bos.toByteArray());
        return is;
    }

}
